package com.koro.service.impl;


import com.koro.dao.GoodsRepository;
import com.koro.dto.FindGoodsDTO;
import com.koro.dto.SaveGoodsDTO;
import com.koro.entity.Goods;
import com.koro.mapper.GoodsMapper;
import com.koro.service.GoodsService;
import com.koro.vo.FindGoodsVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsRepository goodsRepository;

    @Override
    public Integer save(SaveGoodsDTO dto) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(dto,goods);
        if("".equals(dto.getId()) || dto.getId() == 0) {
            goodsMapper.insert(goods);
        } else {
            goodsMapper.updateById(goods);
        }
        return goods.getId();
    }

    @Override
    public List<FindGoodsVO> findAll(FindGoodsDTO dto) {
        // mysql查询
        /*QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(dto.getKeywords())) {
            queryWrapper.like("goods_name",dto.getKeywords());
        }
        List<Goods> goods = goodsMapper.selectList(queryWrapper);
        List<FindGoodsVO> vos = new ArrayList<>();
        goods.forEach(s -> {
            FindGoodsVO findGoodsVO = new FindGoodsVO();
            BeanUtils.copyProperties(s,findGoodsVO);
            vos.add(findGoodsVO);
        });

        return vos;*/

        // es查询
        List<FindGoodsVO> vos = new ArrayList<>();
        // 查询所有
        Iterable<Goods> all = goodsRepository.findAll();
        // 条件分页查询
        PageRequest pageRequest = PageRequest.of(1 - 1, 10);
        Page<Goods> page = null;
        if(!StringUtils.isEmpty(dto.getKeywords())) {
            page = goodsRepository.findByGoodsNameLike(dto.getKeywords(), pageRequest);
        } else {
            page = goodsRepository.findAll(pageRequest);
        }

        page.forEach(g -> {
            FindGoodsVO vo = new FindGoodsVO();
            BeanUtils.copyProperties(g,vo);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public FindGoodsVO findById(FindGoodsDTO dto) {
        Goods goods = goodsMapper.selectById(dto.getId());
        FindGoodsVO findGoodsVO = new FindGoodsVO();
        BeanUtils.copyProperties(goods, findGoodsVO);
        return findGoodsVO;
    }

    @Override
    public Integer updataseckill(Integer id) {
        return goodsMapper.updataseckill(id);
    }
}
